import { useEffect, useState } from 'react';
import { getLoadMapList, getTenantID, getUserDepID } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import { Form, TreeSelect, Select, message } from 'antd';
import { UpdateMaterielView } from './UpdateMaterielView';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import { findObjectById } from '@/utils/findObjectById';
import { DictionaryRenderFun } from '../../Acommon';

const getUpdateConfig = ({ pageType, record, curRes, setMainAsset, openAssetModalStatus, changeCompanyId }) => {
  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //来源类型
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //品牌类型
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, // 计量单位
  ]);

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 区分选资管部门、使用部门 */
  const [type, setType] = useState<string>('both');

  /** 表单数据 */
  const [combinationForm] = Form.useForm();

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (res && res?.msgFlag) {
      setUserDataList({
        data: getUserList,
        loading: getUserLoading,
      });
      return;
      if (type === 'user') {
        setUserDataList({
          data: getUserList,
          loading: getUserLoading,
        });
      } else if (type === 'admin') {
        setAdminDataList({
          data: getUserList,
          loading: getUserLoading,
        });
      } else {
        setUserDataList({
          data: getUserList,
          loading: getUserLoading,
        });
        setAdminDataList({
          data: getUserList,
          loading: getUserLoading,
        });
      }
    } else {
      message.error(res?.msg);
    }
  });

  /** 获取当前资管部门用户数据 */
  const [adminDataList, setAdminDataList] = useState<any>({
    data: getUserList,
    loading: getUserLoading,
  });

  /** 获取当前使用部门用户数据 */
  const [userDataList, setUserDataList] = useState<any>({
    data: getUserList,
    loading: getUserLoading,
  });

  /** 获取当前部门用户数据 */
  const changeGetUser = (value: string | number, type: string) => {
    if (type === 'admin') {
      /** 置空当前选中的资管人 */
      combinationForm?.setFieldValue('asseterID', '');
    } else {
      /** 置空当前选中的使用人 */
      combinationForm?.setFieldValue('userID', '');
    }
    getUserRun({
      /** 获取当前使用部门用户信息 */
      userDepartmentID: value,
    });
  };

  useEffect(() => {}, [userDataList]);

  // useEffect(() => {
  //   if (loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`] && loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`].length !== 0) {
  //     let obj = findObjectById(`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}1007`, loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`], 'id');
  //     if (Object.keys(obj).length !== 0) {
  //       combinationForm.setFieldValue('assetClassCode', obj?.shortCode);
  //     }
  //   }
  // }, [loadMapInfo]);

  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    if (pageType === 'add') {
      getUserRun({
        //获取当前部门用户信息
        userDepartmentID: getUserDepID(),
      });
    } else {
      getUserRun({
        //获取当前部门用户信息
        userDepartmentID: record?.useDepartmentID,
      });
    }
    /** 回填新增数据 */
    combinationForm?.setFieldsValue({
      ...record,
    });
  }, [record]);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: combinationForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '',
        fieldChildren: [
          {
            field: `assetName`,
            label: `资产名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: disabled ? false : true,
          },
          // {
          //   field: `assetClass`,
          //   label: `资产分类`,
          //   disabled: true,
          //   component: 'Render',
          //   required: false,
          //   render: (text) => {
          //     return (
          //       <TreeSelect
          //         loading={mapLoading}
          //         placeholder="请选择"
          //         treeData={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`]}
          //         disabled={true}
          //         showArrow={pageType == 'detail' ? false : true}
          //         fieldNames={{
          //           label: 'name',
          //           value: 'id',
          //           children: 'children',
          //         }}
          //         showSearch={true}
          //         treeNodeFilterProp={'text'}
          //         allowClear={true}
          //         onChange={(value: string | number) => {
          //           let obj = findObjectById(value, loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`], 'id');
          //           if (Object.keys(obj).length !== 0) {
          //             combinationForm.setFieldValue('assetClassCode', obj?.shortCode);
          //           }
          //         }}
          //       />
          //     );
          //   },
          // },
          {
            field: `sourceType`,
            label: `资产来源`,
            disabled: true,
            component: 'Render',
            required: false,
            render: (text) => {
              if (disabled) {
                return <span>{record?.sourceTypeName ? record?.sourceTypeName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <Select
                    loading={mapLoading}
                    options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`]}
                    disabled={true}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                    }}
                  />
                );
              }
            },
          },
          // {
          //   field: `assetClassCode`,
          //   label: `资产分类编码`,
          //   component: 'Input',
          //   disabled: true,
          //   placeholder: '自动带出',
          //   required: false,
          // },
          {
            field: `assetCode`,
            label: `资产编号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `paramsInfo`,
            label: `规格型号`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: true,
          },
          {
            field: `quantityOrArea`,
            label: `数量`,
            component: 'InputNumber',
            placeholder: '请输入',
            disabled: disabled,
            required: disabled ? false : true,
            min: 0,
            // contentAfter: '元',
            pattern: RegularExpression?.number,
            patternMsg: '请输入整数',
          },
          {
            field: `unitOfMeasurement`,
            label: `计量单位`,
            component: 'Render',
            disabled: disabled,
            placeholder: '请输入',
            required: disabled ? false : true,
            render: (text) => {
              if (disabled) {
                return <span>{record?.unitOfMeasurementName ? record?.unitOfMeasurementName.split('||')[0] : ''}</span>;
              } else {
                return (
                  <Select
                    loading={mapLoading}
                    options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]}
                    disabled={disabled}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                    }}
                  />
                );
              }
            },
          },
          {
            field: `assetOldPrice`,
            label: `资产原值`,
            component: 'InputNumber',
            placeholder: '自动带出',
            disabled: true,
            initialValue: 0,
            contentAfter: '元',
          },
          {
            field: `assetValue`,
            label: `参考价值`,
            component: 'InputNumber',
            placeholder: '请输入',
            disabled: disabled,
            required: disabled ? false : true,
            min: 0,
            contentAfter: '元',
            pattern: RegularExpression?.twoFloatNumber,
            patternMsg: '请输入整数或保留两位小数',
          },
          // {
          //   field: `assetDepartmentID`,
          //   label: `资管部门`,
          //   disabled: disabled,
          //   component: 'Render',
          //   required: true,
          //   render: (text) => {
          //     return (
          //       <TreeSelect
          //         loading={getFlowOrgTreeLoading}
          //         placeholder="请选择"
          //         treeData={handleNotPostion(getFlowOrgList)}
          //         disabled={pageType == 'detail' ? true : false}
          //         showArrow={pageType == 'detail' ? false : true}
          //         fieldNames={{
          //           label: 'title',
          //           value: 'id',
          //           children: 'children',
          //         }}
          //         showSearch={true}
          //         treeNodeFilterProp={'text'}
          //         allowClear={true}
          //         onChange={(value: string | number) => {
          //           adminDataList.loading = true;
          //           setAdminDataList(adminDataList);
          //           setType('admin');
          //           changeGetUser(value, 'admin');
          //         }}
          //       />
          //     );
          //   },
          // },
          // {
          //   field: `asseterID`,
          //   label: `资管人`,
          //   disabled: disabled,
          //   component: 'Render',
          //   required: true,
          //   render: (text) => {
          //     return (
          //       <Select
          //         loading={adminDataList.loading}
          //         options={adminDataList.data}
          //         disabled={disabled}
          //         placeholder="请选择"
          //         fieldNames={{
          //           label: 'realName',
          //           value: 'id',
          //         }}
          //       />
          //     );
          //   },
          // },
          {
            field: `useDepartmentID`,
            label: `使用部门`,
            disabled: true,
            component: 'Render',
            required: false,
            render: (text) => {
              return (
                <TreeSelect
                  loading={getFlowOrgTreeLoading}
                  placeholder="请选择"
                  treeData={handleNotPostion(getFlowOrgList)}
                  disabled={disabled}
                  showArrow={pageType == 'detail' ? false : true}
                  fieldNames={{
                    label: 'title',
                    value: 'id',
                    children: 'children',
                  }}
                  showSearch={true}
                  treeNodeFilterProp={'text'}
                  allowClear={true}
                  onSelect={(value: string | number, node: any) => {
                    userDataList.loading = true;
                    setUserDataList(userDataList);
                    setType('user');
                    changeGetUser(value, 'user');
                    // 获取出当前使用部门的单位
                    changeCompanyId(node?.attributes.companyID);
                    // combinationForm.setFieldValue('useCompanyID', node?.attributes.companyID);
                  }}
                />
              );
            },
          },
          {
            field: `userID`,
            label: `使用人`,
            disabled: true,
            component: 'Render',
            required: false,
            render: (text) => {
              if (disabled) {
                return <span>{record?.userName ? record?.userName : '--'}</span>;
              } else {
                return (
                  <Select
                    loading={userDataList.loading}
                    options={userDataList.data}
                    disabled={disabled}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'realName',
                      value: 'id',
                    }}
                  />
                );
              }
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '',
        fieldCustomDom: <UpdateMaterielView pageType={pageType} openAssetModalStatus={openAssetModalStatus} setMainAsset={setMainAsset} />,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
